﻿namespace B13_Ex01_4
{
    public static class Program
    {
        public static void Main()
        {
            StringToBin.Run();
            System.Console.WriteLine("Press Enter to Exit...");
            System.Console.ReadLine();
        }
    }

    public static class StringToBin
    {
        public static void Run()
        {
            System.Console.WriteLine("Please enter a binary number (10 chars):");
            string binaryString = System.Console.ReadLine();
            char[] binaryCharArray = binaryString.ToCharArray();
            if (isValidBinaryNumber(binaryCharArray))
            {
                System.Console.WriteLine("String is a valid binary number\nString Length is 10 chars");
                if (isPrimeNumber(binaryToDecimal(binaryCharArray)))
                {
                    System.Console.WriteLine("Number is a prime number");
                }
                else
                {
                    System.Console.WriteLine("Number is not a prime number");
                }
            }
        }

        private static bool isValidBinaryNumber(char[] i_BinaryCharArray)
        {
            bool isValid = true;

            foreach (char bit in i_BinaryCharArray)
            {
                if (bit != '0' && bit != '1')
                {
                    isValid = !isValid;
                    System.Console.WriteLine("Input string is not a binary number");
                }
            }

            if (i_BinaryCharArray.Length != 10)
            {
                isValid = !isValid;
                System.Console.WriteLine("String length is not 10 chars");
            }
            
            return isValid;
        }

        private static int binaryToDecimal(char[] i_BinaryCharArray)
        {
            int result = 0;
            for (int i = 1, j = 9; i < 1024; i *= 2, j--)
            {
                if (i_BinaryCharArray[j] == '1')
                {
                    result += i;
                }
            }

            System.Console.WriteLine("Number in decimal: " + result);
            return result;
        }

        private static bool isPrimeNumber(int i_stringInDecimal)
        {
            bool isPrime = true;
            int endOfLoop = (int)System.Math.Sqrt(i_stringInDecimal);
            for (int i = 2; i < endOfLoop; i++)
            {
                if ((i_stringInDecimal % i) == 0)
                {
                    return !isPrime;
                }
            }

            return isPrime;
        }
    }
}
